<template>
  <div class="station-view-container">


    <!-- Station Cards Grid -->
    <div class="cards-section">
      <el-row :gutter="24" v-loading="loading">
        <el-col
          v-for="station in filteredStations"
          :key="station.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="6"
          class="station-col"
        >
          <el-card 
            class="station-card" 
            :class="getCardClass(station)"
            shadow="hover"
          >
            <div class="card-header">
              <div class="station-status" :class="getStatusClass(station.isEnable)">
                <el-icon><CircleCheck v-if="station.isEnable === 1" /><CircleClose v-else /></el-icon>
              </div>
              <div class="station-type">
                <el-tag :type="getStorageTypeTag(station.staitonStorageType)" size="small">
                  {{ getStorageTypeName(station.staitonStorageType) }}
                </el-tag>
              </div>
            </div>

            <div class="card-body">
              <h3 class="station-name">
                {{ locale ? station.stationCnName : station.stationEnName }}
              </h3>
              <p class="station-pkey">{{ station.pkey }}</p>
              
              <div class="station-stats">
                <div class="stat-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatDate(station.createTime) }}</span>
                </div>
                <div class="stat-item">
                  <el-icon><Edit /></el-icon>
                  <span>{{ formatDate(station.updateTime) }}</span>
                </div>
              </div>

              <div class="station-actions">
                <el-button
                  type="primary"
                  text
                  @click="viewStation(station)"
                  icon="View"
                >
                  {{ $t('common.view') }}
                </el-button>
                <el-button
                  type="primary"
                  text
                  @click="editStation(station)"
                  icon="Edit"
                >
                  {{ $t('common.edit') }}
                </el-button>
                <el-button
                  type="success"
                  text
                  @click="viewGateway(station)"
                  icon="Connection"
                >
                  {{ $t('common.gateway') }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- Empty State -->
      <div v-if="!loading && filteredStations.length === 0" class="empty-state">
        <el-empty :description="$t('common.noData')">
          <template #image>
            <el-icon class="empty-icon"><OfficeBuilding /></el-icon>
          </template>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  OfficeBuilding, 
  House, 
  Check, 
  Close, 
  CircleCheck, 
  CircleClose,
  Clock,
  Edit,
  Connection,
  View
} from '@element-plus/icons-vue'
import { getstationListApi } from '@/api/ems/station/station.ts'
import { getEnumListByType } from '@/api/enums'
import { EmsCommonEnums } from '@/enum/common/EmsCommonEnums.ts'
import { staitonEnum } from '@/enum/staitonEnum'

const { t } = useI18n()
const router = useRouter()

// Data
const loading = ref(false)
const stationList = ref([])
const locale = ref(window.localStorage.getItem('locale') === 'zh-CN')

// Filter form
const filterForm = reactive({
  stationId: '',
  status: ''
})

// Status options
const statusOptions = ref([
  { value: '1', label: t('common.enable') },
  { value: '0', label: t('common.disable') }
])

// Storage type enums
const storageTypeEnums = ref([])

// Computed
const total = computed(() => stationList.value.length)
const enabledStations = computed(() => 
  stationList.value.filter(item => item.isEnable === 1).length
)

const filteredStations = computed(() => {
  let filtered = stationList.value

  if (filterForm.stationId) {
    filtered = filtered.filter(station => station.id === filterForm.stationId)
  }

  if (filterForm.status !== '') {
    const status = parseInt(filterForm.status)
    filtered = filtered.filter(station => station.isEnable === status)
  }

  return filtered
})

// Methods
const loadStations = async () => {
  loading.value = true
  try {
    const response = await getstationListApi()
    stationList.value = response.data || []
  } catch (error) {
    ElMessage.error(t('common.loadError'))
  } finally {
    loading.value = false
  }
}

const loadEnums = async () => {
  try {
    const response = await getEnumListByType({ type: staitonEnum.StaitonStorageTypeEnum })
    storageTypeEnums.value = response.data || []
  } catch (error) {
    console.error('Failed to load storage type enums:', error)
  }
}

const handleSearch = () => {
  // Filtering is handled by computed property
}

const handleReset = () => {
  filterForm.stationId = ''
  filterForm.status = ''
}

const getCardClass = (station) => {
  return {
    'station-active': station.isEnable === 1,
    'station-inactive': station.isEnable === 0
  }
}

const getStatusClass = (isEnable) => {
  return {
    'status-active': isEnable === 1,
    'status-inactive': isEnable === 0
  }
}

const getStorageTypeTag = (type) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info'
  }
  return typeMap[type] || 'info'
}

const getStorageTypeName = (type) => {
  const enumItem = storageTypeEnums.value.find(item => item.code === type)
  return enumItem ? (locale.value ? enumItem.cndesc : enumItem.endesc) : t('common.unknown')
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString()
}

const viewStation = (station) => {
  router.push({ 
    path: '/monitorManagement/operationMonitoring',
    query: { stationId: station.id } 
  })
}

const editStation = (station) => {
  router.push({ 
    path: '/stationMangement/station', 
    query: { edit: true, stationId: station.id } 
  })
}

const viewGateway = (station) => {
  router.push({ 
    path: '/stationMangement/gateway', 
    query: { stationId: station.id } 
  })
}

// Lifecycle
onMounted(() => {
  loadStations()
  loadEnums()
})
</script>

<style lang="scss" scoped>
.station-view-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;

  // Header Section
  .header-section {
    margin-bottom: 24px;

    .header-content {
      background: white;
      border-radius: 16px;
      padding: 24px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(10px);
    }

    .title-wrapper {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 20px;

      .title-icon {
        font-size: 32px;
        color: #667eea;
      }

      .page-title {
        margin: 0;
        font-size: 28px;
        font-weight: 700;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }
    }

    .header-stats {
      display: flex;
      gap: 20px;
      flex-wrap: wrap;

      .stat-card {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px 20px;
        background: linear-gradient(135deg, #f8f9ff 0%, #e8f0ff 100%);
        border-radius: 12px;
        border: 1px solid rgba(102, 126, 234, 0.1);
        min-width: 160px;

        .stat-icon {
          width: 40px;
          height: 40px;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          color: white;

          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }

          &.active {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
          }

          &.inactive {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
          }
        }

        .stat-info {
          display: flex;
          flex-direction: column;

          .stat-value {
            font-size: 20px;
            font-weight: 700;
            color: #2c3e50;
          }

          .stat-label {
            font-size: 12px;
            color: #7f8c8d;
            font-weight: 500;
          }
        }
      }
    }
  }

  // Filter Section
  .filter-section {
    margin-bottom: 24px;

    .filter-card {
      border-radius: 12px;
      border: none;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

      .filter-form {
        .station-select {
          min-width: 200px;
        }
      }
    }
  }

  // Cards Section
  .cards-section {
    .station-col {
      margin-bottom: 24px;
    }

    .station-card {
      border-radius: 16px;
      border: none;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      overflow: hidden;
      height: 100%;

      &:hover {
        transform: translateY(-8px);
        box-shadow: 0 16px 48px rgba(0, 0, 0, 0.15);
      }

      &.station-active {
        background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%);
        border: 2px solid #84fab0;
      }

      &.station-inactive {
        background: linear-gradient(135deg, #ffffff 0%, #fff5f5 100%);
        border: 2px solid #ffecd2;
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .station-status {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;

          &.status-active {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: white;
          }

          &.status-inactive {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            color: white;
          }
        }
      }

      .card-body {
        .station-name {
          margin: 0 0 8px 0;
          font-size: 18px;
          font-weight: 600;
          color: #2c3e50;
          line-height: 1.3;
        }

        .station-pkey {
          margin: 0 0 16px 0;
          font-size: 14px;
          color: #7f8c8d;
          font-family: 'Courier New', monospace;
        }

        .station-stats {
          margin-bottom: 20px;

          .stat-item {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
            font-size: 12px;
            color: #95a5a6;

            .el-icon {
              font-size: 14px;
            }
          }
        }

        .station-actions {
          display: flex;
          gap: 8px;
          padding-top: 16px;
          border-top: 1px solid #ecf0f1;

          .el-button {
            flex: 1;
            padding: 8px 12px;
            font-size: 12px;
            border-radius: 8px;
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 60px 20px;

      .empty-icon {
        font-size: 80px;
        color: #bdc3c7;
        margin-bottom: 20px;
      }
    }
  }
}

// Responsive Design
@media (max-width: 768px) {
  .station-view-container {
    padding: 16px;

    .header-section {
      .header-stats {
        .stat-card {
          flex: 1;
          min-width: auto;
        }
      }
    }

    .filter-section {
      .filter-form {
        .el-form-item {
          display: block;
          margin-bottom: 12px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .station-view-container {
    .header-section {
      .title-wrapper {
        .page-title {
          font-size: 24px;
        }
      }

      .header-stats {
        flex-direction: column;

        .stat-card {
          width: 100%;
        }
      }
    }
  }
}
</style>